extends Control
class_name GameControls

# 游戏控制按钮组件
# 在HUD右上角显示暂停、菜单等控制按钮

signal pause_pressed
signal menu_pressed
signal start_game_pressed
signal quit_game_pressed

# UI节点
var pause_button: TextureButton
var menu_button: TextureButton
var start_button: TextureButton
var quit_button: TextureButton

# 初始化标志
var is_initialized: bool = false

# 按钮尺寸 - 调整为更适合小屏幕的大小
const BUTTON_SIZE = Vector2(20, 20)  # 进一步缩小
const BUTTON_SPACING = 25  # 减少间距

func _ready():
	# 设置处理模式为始终处理 - 确保按钮在所有状态下都能工作
	process_mode = Node.PROCESS_MODE_ALWAYS
	
	if not is_initialized:
		initialize()

func _input(event):
	# 测试：检测点击事件
	if event is InputEventMouseButton and event.pressed:
		print("🖱️ GameControls检测到鼠标点击: ", event.position)
		# 检查点击是否在暂停按钮区域内
		if pause_button and pause_button.visible:
			var button_rect = Rect2(pause_button.global_position, pause_button.size)
			if button_rect.has_point(event.global_position):
				print("📍 点击位置在暂停按钮区域内: ", button_rect)

func initialize():
	if is_initialized:
		print("GameControls 已经初始化过了，跳过重复初始化")
		return
		
	print("GameControls initialize() 开始...")
	
	# 设置高z_index确保按钮在最上层
	z_index = 100
	
	# 不要覆盖场景文件中的尺寸设置，只在必要时设置默认值，增加宽度以容纳退出按钮
	if size == Vector2.ZERO:
		size = Vector2(BUTTON_SPACING * 4, BUTTON_SIZE.y + 10)  # 增加一个按钮的宽度
	
	# 检查当前锚点设置
	print("当前锚点设置 - Left:", anchor_left, " Right:", anchor_right, " Top:", anchor_top, " Bottom:", anchor_bottom)
	
	# 只在锚点还是默认值时才设置右上角锚点
	if anchor_left == 0.0 and anchor_right == 0.0:
		print("设置右上角锚点...")
		anchors_preset = Control.PRESET_TOP_RIGHT
		position = Vector2(-size.x - 10, 10)
	else:
		print("锚点已设置，使用场景中的配置")
	
	create_buttons()
	
	is_initialized = true
	print("GameControls 初始化完成，尺寸: ", size, " 位置: ", position, " 锚点: L=", anchor_left, " R=", anchor_right, " z_index: ", z_index)

func create_buttons():
	print("创建游戏控制按钮...")
	
	# 创建开始游戏按钮
	start_button = TextureButton.new()
	add_child(start_button)
	start_button.texture_normal = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button.png")
	start_button.texture_pressed = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button_press.png")
	start_button.position = Vector2(5, 5)
	start_button.custom_minimum_size = BUTTON_SIZE  # 强制最小尺寸
	start_button.size = BUTTON_SIZE  # 强制设置尺寸
	start_button.ignore_texture_size = true  # 忽略贴图原始尺寸
	start_button.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
	start_button.pressed.connect(_on_start_button_pressed)
	start_button.tooltip_text = "开始游戏"
	# 确保按钮可以接收输入
	start_button.mouse_filter = Control.MOUSE_FILTER_PASS
	# 延迟设置尺寸确保生效
	call_deferred("_force_button_size", start_button)
	# 添加按钮文字标签
	add_button_label(start_button, "开始", Color.WHITE)
	print("开始游戏按钮创建完成，位置: ", start_button.position, " 尺寸: ", start_button.size, " 可见: ", start_button.visible, " 鼠标过滤: ", start_button.mouse_filter)
	
	# 创建退出游戏按钮（在开始界面显示）
	quit_button = TextureButton.new()
	add_child(quit_button)
	quit_button.texture_normal = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button.png")
	quit_button.texture_pressed = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button_press.png")
	quit_button.position = Vector2(BUTTON_SPACING + 5, 5)
	quit_button.custom_minimum_size = BUTTON_SIZE
	quit_button.size = BUTTON_SIZE
	quit_button.ignore_texture_size = true
	quit_button.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
	quit_button.pressed.connect(_on_quit_button_pressed)
	quit_button.tooltip_text = "退出游戏"
	quit_button.mouse_filter = Control.MOUSE_FILTER_PASS
	call_deferred("_force_button_size", quit_button)
	add_button_label(quit_button, "退出", Color.RED)  # 使用红色突出显示
	print("退出游戏按钮创建完成，位置: ", quit_button.position, " 尺寸: ", quit_button.size)
	
	# 创建暂停按钮
	pause_button = TextureButton.new()
	add_child(pause_button)
	pause_button.texture_normal = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/pause_button.png")
	pause_button.texture_pressed = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/pause_button_press.png")
	pause_button.position = Vector2(BUTTON_SPACING * 2 + 5, 5)  # 调整位置
	pause_button.custom_minimum_size = BUTTON_SIZE  # 强制最小尺寸
	pause_button.size = BUTTON_SIZE  # 强制设置尺寸
	pause_button.ignore_texture_size = true  # 忽略贴图原始尺寸
	pause_button.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
	pause_button.pressed.connect(_on_pause_button_pressed)
	pause_button.tooltip_text = "暂停游戏"
	pause_button.visible = false  # 游戏开始前隐藏
	# 确保按钮可以接收输入
	pause_button.mouse_filter = Control.MOUSE_FILTER_PASS
	# 添加按钮文字标签
	add_button_label(pause_button, "暂停", Color.WHITE)
	print("暂停按钮创建完成，位置: ", pause_button.position, " 尺寸: ", pause_button.size, " 可见: ", pause_button.visible, " 鼠标过滤: ", pause_button.mouse_filter)
	
	# 创建菜单按钮
	menu_button = TextureButton.new()
	add_child(menu_button)
	menu_button.texture_normal = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button.png")
	menu_button.texture_pressed = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/menu_button_press.png")
	menu_button.position = Vector2(BUTTON_SPACING * 3 + 5, 5)  # 调整位置
	menu_button.custom_minimum_size = BUTTON_SIZE  # 强制最小尺寸
	menu_button.size = BUTTON_SIZE  # 强制设置尺寸
	menu_button.ignore_texture_size = true  # 忽略贴图原始尺寸
	menu_button.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
	menu_button.pressed.connect(_on_menu_button_pressed)
	menu_button.tooltip_text = "游戏菜单"
	menu_button.visible = false  # 游戏开始前隐藏
	# 延迟设置尺寸确保生效
	call_deferred("_force_button_size", menu_button)
	# 添加按钮文字标签
	add_button_label(menu_button, "菜单", Color.WHITE)
	print("菜单按钮创建完成，位置: ", menu_button.position, " 尺寸: ", menu_button.size, " 可见: ", menu_button.visible)
	
	print("所有按钮创建完成")

func _on_start_button_pressed():
	print("🖱️ 开始游戏按钮被点击")
	start_game_pressed.emit()
	print("📤 发出start_game_pressed信号")
	
	# 隐藏开始界面按钮，显示游戏控制按钮
	start_button.visible = false
	quit_button.visible = false  # 隐藏退出按钮
	pause_button.visible = true
	menu_button.visible = true
	print("🔄 按钮可见性已更新")
	
	# 按钮点击动画
	animate_button(start_button)

func _on_quit_button_pressed():
	print("🚪 退出游戏按钮被点击")
	quit_game_pressed.emit()
	print("📤 发出quit_game_pressed信号")
	
	# 按钮点击动画
	animate_button(quit_button)

func _on_pause_button_pressed():
	print("🖱️ 暂停/继续按钮被点击")
	pause_pressed.emit()
	print("📤 发出pause_pressed信号")
	
	# 按钮点击动画
	animate_button(pause_button)

func _on_menu_button_pressed():
	menu_pressed.emit()
	
	# 按钮点击动画
	animate_button(menu_button)

func animate_button(button: TextureButton):
	# 按钮点击动画效果
	var tween = create_tween()
	tween.tween_property(button, "scale", Vector2(0.9, 0.9), 0.1)
	tween.tween_property(button, "scale", Vector2(1.0, 1.0), 0.1)

func set_pause_button_state(paused: bool):
	# 根据暂停状态改变按钮外观和文字
	if pause_button:
		print("🔄 设置暂停按钮状态: ", paused, " 按钮可见: ", pause_button.visible, " 按钮位置: ", pause_button.global_position)
		
		# 找到按钮中的文字标签
		var label = null
		for child in pause_button.get_children():
			if child is Label:
				label = child
				break
		
		if paused:
			pause_button.modulate = Color.YELLOW
			pause_button.tooltip_text = "继续游戏 (ESC键)"
			if label:
				label.text = "继续"
				label.add_theme_color_override("font_color", Color.BLACK)
				print("✅ 按钮文字已更新为: 继续")
		else:
			pause_button.modulate = Color.WHITE
			pause_button.tooltip_text = "暂停游戏 (ESC键)"
			if label:
				label.text = "暂停"
				label.add_theme_color_override("font_color", Color.WHITE)
				print("✅ 按钮文字已更新为: 暂停")

func reset_to_start_screen():
	# 重置到开始界面状态
	start_button.visible = true
	quit_button.visible = true  # 显示退出按钮
	pause_button.visible = false
	menu_button.visible = false

# 强制设置按钮尺寸的辅助方法
func _force_button_size(button: TextureButton):
	if button:
		button.size = BUTTON_SIZE
		button.custom_minimum_size = BUTTON_SIZE
		print("强制设置按钮尺寸: ", button.size)

# 为按钮添加文字标签的辅助方法
func add_button_label(button: TextureButton, text: String, color: Color = Color.WHITE):
	if not button:
		return
	
	# 创建标签
	var label = Label.new()
	button.add_child(label)
	
	# 设置标签文字和样式
	label.text = text
	label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	label.add_theme_color_override("font_color", color)
	label.add_theme_color_override("font_shadow_color", Color.BLACK)
	label.add_theme_constant_override("shadow_offset_x", 1)
	label.add_theme_constant_override("shadow_offset_y", 1)
	label.add_theme_font_size_override("font_size", 8)  # 增大字体以提高清晰度
	
	# 设置标签尺寸和位置，覆盖整个按钮
	label.size = BUTTON_SIZE
	label.position = Vector2.ZERO
	
	# 设置标签不接收鼠标事件，让按钮可以正常点击
	label.mouse_filter = Control.MOUSE_FILTER_IGNORE
	print("标签鼠标过滤设置为: ", label.mouse_filter)
	
	# 创建默认字体资源并启用抗锯齿
	var font = SystemFont.new()
	font.font_names = ["Arial", "Microsoft YaHei", "SimSun"]  # 支持中文的字体
	font.antialiasing = TextServer.FONT_ANTIALIASING_GRAY
	font.hinting = TextServer.HINTING_LIGHT
	label.add_theme_font_override("font", font)
	
	print("为按钮添加文字标签: ", text)

# 响应屏幕尺寸变化
func _notification(what):
	if what == NOTIFICATION_RESIZED:
		if get_viewport():
			# 重新计算右上角位置
			anchors_preset = Control.PRESET_TOP_RIGHT
			position = Vector2(-size.x - 10, 10) 
